package com.scm.biz.service._impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.scm.biz.bean.Area;
import com.scm.biz.bean.BusinessConstant;
import com.scm.biz.bean.Constant;
import com.scm.biz.bean.Factory;
import com.scm.biz.bean.FactoryContact;
import com.scm.biz.dao.AreaDao;
import com.scm.biz.dao.BusinessConstantDao;
import com.scm.biz.dao.ConstantDao;
import com.scm.biz.dao.FactoryContactDao;
import com.scm.biz.dao.FactoryDao;
import com.scm.biz.dto.FactoryDto;
import com.scm.biz.enums.FileCategoryEnum;
import com.scm.biz.query.BusinessConstantQuery;
import com.scm.biz.query.FactoryQuery;
import com.scm.biz.result.FactoryResult;
import com.scm.biz.service.FactoryService;
import com.scm.core.bean.exp.UfdmException;
import com.scm.utils.Const;
import com.scm.utils.UploadAndDownUtil;

/**
 * 工厂模块业务层接口实现类
 * 
 * @author 张乐锋
 *
 */
@Service
public class FactoryServiceImpl implements FactoryService {

	@Resource
	private FactoryDao factoryDao;
	@Resource
	private AreaDao areaDao;
	@Resource
	private BusinessConstantDao businessConstantDao;
	@Resource
	private ConstantDao constantDao;
	@Resource
	private FactoryContactDao factoryContactDao;

	/**
	 * 获取工厂列表
	 * 
	 * @param factory
	 *            查询参数（包含查询条件和分页条件,属性可为空）
	 * @return
	 */
	@Override
	public List<FactoryResult> getFactoryList(FactoryQuery factoryQuery) {
		List<FactoryResult> factoryDetails = new ArrayList<FactoryResult>();
		List<Factory> factories = factoryDao.selectAll(factoryQuery);
		for (Factory fac : factories) {
			FactoryResult factoryResult = new FactoryResult(fac);
			Long factoryId = fac.getId();
			Integer proviceId = fac.getProvince_id();
			Integer cityId = fac.getCity_id();
			Integer areaId = fac.getArea_id();
			// 根据省的Id查询省的中文名
			if (proviceId != null) {
				Area province = areaDao.selectByPrimaryKey(proviceId);
				if (province != null) {
					factoryResult.setProvince(province.getArea_name());
				}
			}
			// 根据城市Id查询城市的中文名
			if (cityId != null) {
				Area city = areaDao.selectByPrimaryKey(cityId);
				if (city != null) {
					factoryResult.setCity(city.getArea_name());
				}
			}
			// 根据地区Id查询城市
			if (areaId != null) {
				Area area = areaDao.selectByPrimaryKey(areaId);
				if (area != null) {
					factoryResult.setArea(area.getArea_name());
				}
			}
			BusinessConstantQuery businessConstantQuery = new BusinessConstantQuery();
			businessConstantQuery.setBusinessId(factoryId);
			businessConstantQuery.setCategory("scm_factory-tatting_style");
			List<Integer> tattingStyleIds = businessConstantDao.selectByQuery(businessConstantQuery);
			List<Constant> constants = new ArrayList<Constant>();
			for (Integer id : tattingStyleIds) {
				Constant constant = constantDao.selectByPrimaryKey(id);
				// System.out.println(constant.getName());
				constants.add(constant);
			}
			factoryResult.setTattingStyle(constants);
			businessConstantQuery.setCategory("scm_factory-woven_style");
			List<Integer> wovenStyleIds = businessConstantDao.selectByQuery(businessConstantQuery);
			constants = new ArrayList<Constant>();
			for (Integer id : wovenStyleIds) {
				Constant constant = constantDao.selectByPrimaryKey(id);
				// System.out.println(constant.getName());
				constants.add(constant);
			}
			factoryResult.setWovenStyle(constants);
			businessConstantQuery.setCategory("scm_factory-sweater_style");
			List<Integer> sweaterStyleIds = businessConstantDao.selectByQuery(businessConstantQuery);
			constants = new ArrayList<Constant>();
			for (Integer id : sweaterStyleIds) {
				Constant constant = constantDao.selectByPrimaryKey(id);
				// System.out.println(constant.getName());
				constants.add(constant);
			}
			factoryResult.setSweaterStyle(constants);
			List<FactoryContact> factoryContacts = factoryContactDao.selectByFactoryId(factoryId.intValue());
			factoryResult.setFactoryContacts(factoryContacts);
			factoryDetails.add(factoryResult);
		}
		return factoryDetails;
	}

	/**
	 * 根据Id查询工厂详情
	 * 
	 * @param factoryId
	 * @return
	 */
	@Override
	public FactoryResult getFactoryDetailById(Long factoryId) {
		Factory factory = factoryDao.selectByPrimaryKey((long) factoryId);
		FactoryResult factoryResult = new FactoryResult(factory);
		Integer proviceId = factory.getProvince_id();
		Integer cityId = factory.getCity_id();
		Integer areaId = factory.getArea_id();
		if(proviceId!=null&&proviceId!=0){
			Area province = areaDao.selectByPrimaryKey(proviceId);
			factoryResult.setProvince(province.getArea_name());
		}
		if(cityId!=null&&cityId!=0){
			Area city = areaDao.selectByPrimaryKey(cityId);
			factoryResult.setCity(city.getArea_name());
		}
		if(areaId!=null&&areaId!=0){
			Area area = areaDao.selectByPrimaryKey(areaId);
			factoryResult.setArea(area.getArea_name());
		}
		BusinessConstantQuery businessConstantQuery = new BusinessConstantQuery();
		businessConstantQuery.setBusinessId(factoryId);
		businessConstantQuery.setCategory("scm_factory-tatting_style");
		List<Integer> tattingStyleIds = businessConstantDao.selectByQuery(businessConstantQuery);
		List<Constant> constants = new ArrayList<Constant>();
		for (Integer id : tattingStyleIds) {
			Constant constant = constantDao.selectByPrimaryKey(id);
			constants.add(constant);
		}
		factoryResult.setTattingStyle(constants);
		businessConstantQuery.setCategory("scm_factory-woven_style");
		List<Integer> wovenStyleIds = businessConstantDao.selectByQuery(businessConstantQuery);
		constants = new ArrayList<Constant>();
		for (Integer id : wovenStyleIds) {
			Constant constant = constantDao.selectByPrimaryKey(id);
			constants.add(constant);
		}
		factoryResult.setWovenStyle(constants);
		businessConstantQuery.setCategory("scm_factory-sweater_style");
		List<Integer> sweaterStyleIds = businessConstantDao.selectByQuery(businessConstantQuery);
		constants = new ArrayList<Constant>();
		for (Integer id : sweaterStyleIds) {
			Constant constant = constantDao.selectByPrimaryKey(id);
			constants.add(constant);
		}
		factoryResult.setSweaterStyle(constants);
		List<FactoryContact> factoryContacts = factoryContactDao.selectByFactoryId(factoryId.intValue());
		factoryResult.setFactoryContacts(factoryContacts);
		return factoryResult;
	}

	/**
	 * 插入工厂数据
	 * 
	 * @param factoryDto
	 * @return
	 * @throws UfdmException 
	 */
	@Override
	public boolean insertFactory(FactoryDto factoryDto) throws UfdmException {
		Factory factory = new Factory();
		factory.setCode(Const.getFactoryCode());
		factory.setName(factoryDto.getFactoryName());
		factory.setProvince_id(factoryDto.getProvinceId());
		factory.setCity_id(factoryDto.getCityId());
		factory.setArea_id(factoryDto.getAreaId());
		factory.setDetail_address(factoryDto.getDetailAddress());
		factory.setPerson_amount(factoryDto.getPersonAmount());
		factory.setSale_target(factoryDto.getSaleTarget());
		factory.setCooperation_condition(factoryDto.getCooperationCondition());
		if (factoryDto.getEstimateReport() != null&&!factoryDto.getEstimateReport().isEmpty()) {
			String originFileName = factoryDto.getEstimateReport().getOriginalFilename();
			String filePath = UploadAndDownUtil.uploadFile(factoryDto.getEstimateReport(), FileCategoryEnum.FACTORY_REPORT.value());
			if (filePath != null && !filePath.isEmpty()) {
				factory.setEstimate_report(filePath);
				factory.setOrigin_name(originFileName);
			}
		}
		factory.setCreated_at(new Date());
		factoryDao.insertReturnId(factory);
		Long factoryId = factory.getId();
		// 添加联系人
		FactoryContact factoryContact = new FactoryContact();
		factoryContact.setFactory_id(factoryId.intValue());
		factoryContact.setContact(factoryDto.getContact());
		factoryContact.setLinkman(factoryDto.getLinkman());
		factoryContact.setCreated_at(new Date());
		if (factoryDto.getContact() != null && !factoryDto.getContact().isEmpty() && factoryDto.getLinkman() != null
				&& !factoryDto.getLinkman().isEmpty()) {
			factoryContactDao.insertSelective(factoryContact);
		}
		// 添加梳织类型
		if (factoryDto.getTattingStyleIds() != null && factoryDto.getTattingStyleIds().length != 0) {
			for(int i=0;i<factoryDto.getTattingStyleIds().length;i++){
				BusinessConstant businessConstant = new BusinessConstant();
				businessConstant.setConstant_id(factoryDto.getTattingStyleIds()[i]);
				businessConstant.setBusiness_id(factoryId);
				businessConstant.setCategory("scm_factory-tatting_style");
				businessConstant.setCreated_at(new Date());
				businessConstantDao.insertSelective(businessConstant);
			}
		}
		// 添加针织类型
		if (factoryDto.getWovenStyleIds() != null && factoryDto.getWovenStyleIds().length != 0) {
			for(int i=0;i<factoryDto.getWovenStyleIds().length;i++){
				BusinessConstant businessConstant = new BusinessConstant();
				businessConstant.setConstant_id(factoryDto.getWovenStyleIds()[i]);
				businessConstant.setBusiness_id(factoryId);
				businessConstant.setCategory("scm_factory-woven_style");
				businessConstant.setCreated_at(new Date());
				businessConstantDao.insertSelective(businessConstant);
			}
		}
		// 添加毛衣类型
		if (factoryDto.getSweaterStyleIds() != null && factoryDto.getSweaterStyleIds().length != 0) {
			for(int i=0;i<factoryDto.getSweaterStyleIds().length;i++){
				BusinessConstant businessConstant = new BusinessConstant();
				businessConstant.setConstant_id(factoryDto.getSweaterStyleIds()[i]);
				businessConstant.setBusiness_id(factoryId);
				businessConstant.setCategory("scm_factory-sweater_style");
				businessConstant.setCreated_at(new Date());
				businessConstantDao.insertSelective(businessConstant);
			}
		}
		return true;
	}

	/**
	 * 删除工厂与相关记录
	 * 
	 * @param factoryId
	 * @return
	 */
	@Override
	public boolean deleteFactoryById(Long factoryId) {
		// 删除工厂记录
		int res1 = factoryDao.deleteByPrimaryKey((long) factoryId);
		// 删除业务关系表相关数据
		BusinessConstant businessConstant = new BusinessConstant();
		businessConstant.setBusiness_id(factoryId);
		businessConstant.setCategory("scm_factory-tatting_style");
		businessConstantDao.deleteByBusinessId(businessConstant);
		businessConstant.setCategory("scm_factory-woven_style");
		businessConstantDao.deleteByBusinessId(businessConstant);
		businessConstant.setCategory("scm_factory-sweater_style");
		businessConstantDao.deleteByBusinessId(businessConstant);
		// 删除工厂联系人表相关数据
		factoryContactDao.deleteByFactoryId(factoryId);
		if (res1 >= 1) {
			return true;
		}
		return false;
	}

	@Override
	public boolean updateFactoryById(FactoryDto factoryDto) throws UfdmException {
		Factory factory = new Factory();
		factory.setId(factoryDto.getId());
		factory.setName(factoryDto.getFactoryName());
		factory.setProvince_id(factoryDto.getProvinceId());
		factory.setCity_id(factoryDto.getCityId());
		factory.setArea_id(factoryDto.getAreaId());
		factory.setDetail_address(factoryDto.getDetailAddress());
		factory.setPerson_amount(factoryDto.getPersonAmount());
		factory.setSale_target(factoryDto.getSaleTarget());
		factory.setCooperation_condition(factoryDto.getCooperationCondition());
		if (factoryDto.getEstimateReport() != null&&!factoryDto.getEstimateReport().isEmpty()) {
			String originFileName = factoryDto.getEstimateReport().getOriginalFilename();
			String filePath = UploadAndDownUtil.uploadFile(factoryDto.getEstimateReport(), FileCategoryEnum.FACTORY_REPORT.value());
			if (filePath != null && !filePath.isEmpty()) {
				factory.setEstimate_report(filePath);
				factory.setOrigin_name(originFileName);
			}
		}
		factory.setUpdated_at(new Date());
		// 修改工厂记录
		factoryDao.updateByPrimaryKeySelective(factory);
		// 获取工厂Id
		Long factoryId = factory.getId();
		// 添加联系人
		FactoryContact factoryContact = new FactoryContact();
		factoryContact.setFactory_id(factoryId.intValue());
		factoryContact.setContact(factoryDto.getContact());
		factoryContact.setLinkman(factoryDto.getLinkman());
		factoryContact.setCreated_at(new Date());
		//删除相关联系人
		factoryContactDao.deleteByFactoryId(factoryId);
		// 根据工厂Id插入新的联系人表
		factoryContactDao.insertSelective(factoryContact);
		//先删除该工厂的所有梳织、针织、毛衣类型关联，然后重新插入
		BusinessConstant bc = new BusinessConstant();
		bc.setBusiness_id(factoryId);
		bc.setCategory("scm_factory-tatting_style");
		businessConstantDao.deleteByBusinessId(bc);
		bc.setCategory("scm_factory-woven_style");
		businessConstantDao.deleteByBusinessId(bc);
		bc.setCategory("scm_factory-sweater_style");
		businessConstantDao.deleteByBusinessId(bc);
		// 添加梳织类型
		for(int i=0;i<factoryDto.getTattingStyleIds().length;i++){
			BusinessConstant businessConstant = new BusinessConstant();
			businessConstant.setConstant_id(factoryDto.getTattingStyleIds()[i]);
			businessConstant.setBusiness_id(factoryId);
			businessConstant.setCategory("scm_factory-tatting_style");
			businessConstant.setCreated_at(new Date());
			businessConstantDao.insertSelective(businessConstant);
		}
		// 添加针织类型 
		for(int i=0;i<factoryDto.getWovenStyleIds().length;i++){
			BusinessConstant businessConstant = new BusinessConstant();
			businessConstant.setConstant_id(factoryDto.getWovenStyleIds()[i]);
			businessConstant.setBusiness_id(factoryId);
			businessConstant.setCategory("scm_factory-woven_style");
			businessConstant.setCreated_at(new Date());
			businessConstantDao.insertSelective(businessConstant);
		}
		// 添加毛衣类型
		for(int i=0;i<factoryDto.getSweaterStyleIds().length;i++){
			BusinessConstant businessConstant = new BusinessConstant();
			businessConstant.setConstant_id(factoryDto.getSweaterStyleIds()[i]);
			businessConstant.setBusiness_id(factoryId);
			businessConstant.setCategory("scm_factory-sweater_style");
			businessConstant.setCreated_at(new Date());
			businessConstantDao.insertSelective(businessConstant);
		}
		return true;
	}

	@Override
	public boolean updateEstimateReport(Factory factory) {
		int res = factoryDao.updateByPrimaryKeySelective(factory);
		if(res>=1){
			return true;
		}
		return false;
	}

	@Override
	public int getTotal(FactoryQuery factoryQuery) {
		int total = factoryDao.selectTotal(factoryQuery);
		return total;
	}

	@Override
	public List<Factory> selectList(FactoryQuery factoryQuery) {
		
		return factoryDao.selectList(factoryQuery);
	}

	@Override
	public boolean haveOrder(Integer id) {
		int num = factoryDao.haveOrder(id);
		if(num!=0){
			return true;
		}
		return false;
	}

	@Override
	public String selectOriginName(String estimateReport) {
		String originName =  factoryDao.selectOriginName(estimateReport);
		return originName;
	}

	@Override
	public boolean haveName(String name,Long id) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("name", name);
		map.put("id", id);
		int num = factoryDao.haveName(map);
		if(num==0){
			return true;
		}
		return false;
	}

}
